﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.IO;

public partial class EditRequestAR : System.Web.UI.Page
{

    public Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjUser"].ToString()] = value;
        }
    }


    public bool? IsUser
    {
        get
        {
            if (ViewState["IsUser"] == null)
                ViewState["IsUser"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["IsUser"].ToString()] as bool?;

        }
        set
        {
            if (ViewState["IsUser"] == null)
                ViewState["IsUser"] = System.Guid.NewGuid().ToString();

            Session[ViewState["IsUser"].ToString()] = value;
        }
    }



    public List<TicketMessages> lstGrid
    {
        get
        {
            if (ViewState["lstGrid"] == null)
                ViewState["lstGrid"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["lstGrid"].ToString()] as List<TicketMessages>;
        }
        set
        {
            if (ViewState["lstGrid"] == null)
                ViewState["lstGrid"] = System.Guid.NewGuid().ToString();

            Session[ViewState["lstGrid"].ToString()] = value;
        }
            
    }




    public Ticket mobjTicket
    {
        get
        {
            if (ViewState["mobjTicket"] == null)
                ViewState["mobjTicket"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjTicket"].ToString()] as Ticket;
        }
        set
        {
            if (ViewState["mobjTicket"] == null)
                ViewState["mobjTicket"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjTicket"].ToString()] = value;
        }
    }
    
    
    
    
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            checkSecurityAndCustomizePage();
            bindDdl();
            bindAllControls();
            


        }
    }

    /// <summary>
    /// this function will bind all drop down lists
    /// </summary>
    private void bindDdl()
    {
        TicketPeriorityDB objTicketPeriorityDB = new TicketPeriorityDB(ConnectionStrings.LMS);
        List<TicketPeriority> lstTicketPeriority = objTicketPeriorityDB.Select("", "");

        ddlPeriority.DataSource = lstTicketPeriority;
        ddlPeriority.DataValueField = "ID";
        ddlPeriority.DataTextField = "TicketPeriorityAR";
        ddlPeriority.DataBind();
    }


    /// <summary>
    /// this function will bind the grid with messages
    /// </summary>
    protected void bindGrid()
    {
        lstGrid = new List<TicketMessages>(from obj in mobjTicket.lstTicketMessages orderby obj.ID descending select obj);
        grdUsers.DataSource = lstGrid;
        grdUsers.DataBind();
    }


    /// <summary>
    /// this function will bind all controls with values
    /// </summary>
    private void bindAllControls()
    {
        lblTitleBody.Text = mobjTicket.Title;
        lblDetailsBody.Text = mobjTicket.Details;
        lblRequestSenderBody.Text = mobjTicket.objOwner.getFullNameAR();
        lblRequestTypeBody.Text = mobjTicket.objTicketType.TicketTypeNameAR;
        lblStatusBody.Text = mobjTicket.objTicketStatus.TicketStatusNameAR;

        if (mobjTicket.lstTicketImages.Count > 0)
        {
            pnlRequestImage.Visible = true;

            aImageLink.HRef = "./TicketImages/" + mobjTicket.lstTicketImages[0].TicketImage;

            aImageLink.Target = "_blank";

            imgImage.Src = "getImage.ashx?image=./TicketImages/" + mobjTicket.lstTicketImages[0].TicketImage + "&h=100&w=100&color=white";

        }
        else
        {
            pnlRequestImage.Visible = false;
        }



        bindGrid();

        if (mobjTicket.PeriorityID == -1)
            mobjTicket.PeriorityID = 1;
        
        ddlPeriority.SelectedValue = mobjTicket.PeriorityID.ToString();

        txtNote.Text = mobjTicket.Note;

        lblNoteBody.Text = mobjTicket.Note;


    }



    /// <summary>
    /// this function will check the security of the page with ticket and person and customize this page
    /// </summary>
    private void checkSecurityAndCustomizePage()
    {
        mobjUser = GlobalVars.getCurrentPersonAR();

        if ((!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Ticket_add_page)) && (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Ticket_response_page)) && (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Show_all_requests)))
        {
            Response.Redirect("LoginAR.aspx");
        }

        checkID();


        if ((!mobjUser.Equals(mobjTicket.objOwner)) && (!mobjUser.Equals(mobjTicket.objOperator)) && (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Show_all_requests)))
        {
            Response.Redirect("LoginAR.aspx");
        }


        if (mobjUser.Equals(mobjTicket.objOperator))
        {
            IsUser = false;
            if (mobjTicket.StatusID == 1)
            {
                //open

                pnlMessage.Visible = true;
                pnlOperator.Visible = true;
                pnlUserNote.Visible = false;

                btnClose.Visible = true;
                btnReOpen.Visible = false;
                btnSuspend.Visible = true;

            }
            else if (mobjTicket.StatusID == 2)
            {
                //closed

                pnlMessage.Visible = false;
                pnlOperator.Visible = false;
                pnlUserNote.Visible = true;

                btnClose.Visible = false;
                btnReOpen.Visible = true;
                btnSuspend.Visible = false;


            }
            else if (mobjTicket.StatusID == 3)
            {
                //pending

                pnlMessage.Visible = true;
                pnlOperator.Visible = true;
                pnlUserNote.Visible = false;

                btnClose.Visible = true;
                btnReOpen.Visible = false;
                btnSuspend.Visible = false;

            }
        }
        else if (mobjUser.Equals(mobjTicket.objOwner))
        {
            IsUser = true;

            if (mobjTicket.StatusID == 1)
            {
                //open

                pnlMessage.Visible = true;
                pnlOperator.Visible = false;
                pnlUserNote.Visible = true;

                btnClose.Visible = true;
                btnReOpen.Visible = false;
                btnSuspend.Visible = false;


            }
            else if (mobjTicket.StatusID == 2)
            {
                //closed

                pnlMessage.Visible = false;
                pnlOperator.Visible = false;
                pnlUserNote.Visible = true;

                btnClose.Visible = false;
                btnReOpen.Visible = true;
                btnSuspend.Visible = false;

            }
            else if (mobjTicket.StatusID == 3)
            {
                //pending

                pnlMessage.Visible = true;
                pnlOperator.Visible = false;
                pnlUserNote.Visible = true;

                btnClose.Visible = true;
                btnReOpen.Visible = false;
                btnSuspend.Visible = false;
            }
        }
        else
        {
            pnlMessage.Visible = false;
            pnlOperator.Visible = false;
            pnlUserNote.Visible = true;

            btnClose.Visible = false;
            btnReOpen.Visible = false;
            btnSuspend.Visible = false;
        }




        if (mobjTicket.Note.Equals(String.Empty))
        {
            pnlUserNote.Visible = false;
        }

        


    }


    /// <summary>
    /// this function will check the RequestID for a real value and if not it will redirect to login
    /// </summary>
    private void checkID()
    {
        if (Request["ID"] == null)
            Response.Redirect("LoginAR.aspx");

        long TicketID = -1;

        try { TicketID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("LoginAR.aspx"); }

        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        List<Ticket> lstTicket = objTicketDB.getTicketByID(TicketID);

        if (lstTicket.Count == 0)
            Response.Redirect("LoginAR.aspx");


        mobjTicket = lstTicket[0];






    }






    /// <summary>
    /// this function will get the name of the message sender for grid
    /// </summary>
    /// <param name="strID">the message id</param>
    /// <returns>a string of the sender</returns>
    protected string getMessageSenderName(string strID)
    {
        try
        {




            List<TicketMessages> lstTicketMessages = new List<TicketMessages>(from obj in mobjTicket.lstTicketMessages where obj.ID == long.Parse(strID) select obj);






            TicketMessages objTicketMessages = lstTicketMessages[0];


            if (objTicketMessages.IsUser)
            {
                return mobjTicket.objOwner.Name_AR;
            }
            else
            {
                return mobjTicket.objOperator.Name_AR;
            }
        }
        catch
        {
            return "";
        }

        

    }

    protected void btnSendMessage_Click(object sender, EventArgs e)
    {
        
        if (!randomImage.isOk)
        {
            randomImage.clear();
            lblError.Text = "يجب كتابة الكلمة العشوائية كما هي !";
            bindGrid();
            return;
        }


        TicketMessages tm = new TicketMessages();
        tm.TicketID = mobjTicket.ID;
        tm.IsUser = IsUser.Value;
        tm.Message = txtMessage.Text;

        TicketMessagesDB objTicketMessages = new TicketMessagesDB(ConnectionStrings.LMS);
        objTicketMessages.Insert(tm);


        if (fuImage.HasFile)
        {
            try
            {
                FileInfo fi = new FileInfo(fuImage.FileName);

                string strMessageImage = System.Guid.NewGuid().ToString() + fi.Extension;
                fuImage.SaveAs(Server.MapPath("./TicketImages/" + strMessageImage));
                TicketImagesDB objTicketImagesDB = new TicketImagesDB(ConnectionStrings.LMS);
                TicketImages objTicketImages = new TicketImages();
                objTicketImages.MessageID = tm.ID;
                objTicketImages.TicketID = tm.TicketID;
                objTicketImages.TicketImage = strMessageImage;
                objTicketImagesDB.Insert(objTicketImages);

            }
            catch
            {
            }
        }

             
        
        mobjTicket.clear();



        //sending a mail message
        if (IsUser.Value)
        {
            
            string strMessage = (mobjTicket.objOwner.getFullNameAR() + " يقول\r\n" + tm.MessageDate.ToString("dd/MM/yyyy\r\nHH:mm:ss") + "\r\n" + tm.Message + "\r\n" + "في نظام \"أنا أتعلم\"").Replace("\r\n","<br />");

                GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " رسالة جديدة ",GlobalVars.buildMailBody(strMessage,true) , mobjTicket.objOperator.Email);

            
        }
        else
        {
            string strMessage =  (mobjTicket.objOperator.getFullNameAR() + " يقول\r\n" + tm.MessageDate.ToString("dd/MM/yyyy\r\nHH:mm:ss") + "\r\n" + tm.Message + "\r\n" + "في نظام \"أنا أتعلم\"" ).Replace("\r\n","<br />");
            
                GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " رسالة جديدة ",GlobalVars.buildMailBody(strMessage,true), mobjTicket.objOwner.Email);

            
        }
        //end of sending the mail message
        


        bindGrid();


        lblResult.Text = "تم ارسال الرسالة بنجاح.";

        //updating modify time of ticket
        RefreshTicket();

        mobjTicket.ModifyTime = DateTime.Now;


        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        objTicketDB.Update(mobjTicket);
        //end of updating modify time



        randomImage.clear();
       
    }



    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind();
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        RefreshTicket();

        long perID = long.Parse(ddlPeriority.SelectedValue);

        mobjTicket.Note = txtNote.Text;
        mobjTicket.PeriorityID = perID;

        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        objTicketDB.Update(mobjTicket);

        lblResult.Text = "تم تحديث الطلب بنجاح.";


        string strMailMessage =  "لقد قام مسؤول الدعم الفني لدينا بتحديث طلبك" + " في نظام \"أنا أتعلم\" ";

            GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " تغير", GlobalVars.buildMailBody(strMailMessage,true) , mobjTicket.objOwner.Email);


        
       


        checkSecurityAndCustomizePage();
        bindAllControls();

    }


    /// <summary>
    /// this function will reload Ticket from database
    /// </summary>
    private void RefreshTicket()
    {
        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        List<Ticket> lstTicket = objTicketDB.getTicketByID(mobjTicket.ID);

        if (lstTicket.Count == 0)
            mobjTicket = new Ticket();
        else
            mobjTicket = lstTicket[0];


    }
    protected void btnClose_Click(object sender, EventArgs e)
    {
        RefreshTicket();

        mobjTicket.StatusID = 2;


        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        objTicketDB.Update(mobjTicket);

        lblResult.Text = "تم اغلاق الطلب بنجاح.";

        //sending a mail message
        if (IsUser.Value)
        {
            string strMailMessage = mobjTicket.objOwner.getFullNameAR() + " اغلق الطلب رقم " + mobjTicket.ID.ToString() + " في نظام \"أنا أتعلم\" .";

            GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " تم اغلاقه",GlobalVars.buildMailBody(strMailMessage,true) , mobjTicket.objOperator.Email);


        }
        else
        {
            string strMailMessage = mobjTicket.objOwner.getFullNameAR() + " اغلق الطلب رقم " + mobjTicket.ID.ToString() + " في نظام \"أنا أتعلم\"";

            GlobalVars.SendRequestMail("الطلب رقم  " + mobjTicket.ID.ToString() + " تم اغلاقه",GlobalVars.buildMailBody(strMailMessage,true) , mobjTicket.objOwner.Email);


        }
        //end of sending the mail message


        checkSecurityAndCustomizePage();
        bindAllControls();
    }

    protected void btnReOpen_Click(object sender, EventArgs e)
    {
        RefreshTicket();

        mobjTicket.StatusID = 1;


        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        objTicketDB.Update(mobjTicket);

        lblResult.Text = "تم اعادة تفعيل الطلب بنجاح.";


        //sending a mail message
        if (IsUser.Value)
        {
            string strMailMessage  =  mobjTicket.objOwner.getFullNameAR() + " قام باعادة تفعيل الطلب رقم  " + mobjTicket.ID.ToString() + " في نظام \"أنا أتعلم\"";

            GlobalVars.SendRequestMail("الطلب رقم  " + mobjTicket.ID.ToString() + " تم اعادة تفعيله",GlobalVars.buildMailBody(strMailMessage,true), mobjTicket.objOperator.Email);


        }
        else
        {
            string strMailMessage = mobjTicket.objOwner.getFullNameAR() + " قام باعادة تفعيل الطلب رقم " + mobjTicket.ID.ToString() + " في نظام \"أنا أتعلم\"" ;
            GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " تم اعادة تفعيله", GlobalVars.buildMailBody(strMailMessage,true)  , mobjTicket.objOwner.Email);


        }
        //end of sending the mail message


        checkSecurityAndCustomizePage();
        bindAllControls();
    }
    protected void btnSuspend_Click(object sender, EventArgs e)
    {
        RefreshTicket();

        mobjTicket.StatusID = 3;


        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);
        objTicketDB.Update(mobjTicket);

        lblResult.Text = "تم تعليق الطلب بنجاح.";


        string strMailMessage = mobjTicket.objOwner.getFullNameAR() + " قام بتعليق الطلب حيث انه يحتاج الى وقت اكثر لعرضه على جهات اخرى. " + mobjTicket.ID.ToString() + " في نظام \"أنا أتعلم\"";

        GlobalVars.SendRequestMail("الطلب رقم " + mobjTicket.ID.ToString() + " معلق", GlobalVars.buildMailBody (strMailMessage,true) , mobjTicket.objOwner.Email);


       


        checkSecurityAndCustomizePage();
        bindAllControls();
    }
    protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            long lMessageID = 0;
            long.TryParse(grdUsers.DataKeys[e.Row.RowIndex]["ID"].ToString(), out lMessageID);

            TicketMessagesDB objTicketMessagesDB = new TicketMessagesDB(ConnectionStrings.LMS);
            List<TicketMessages> lstTicketMessages = objTicketMessagesDB.getTicketMessagesByID(lMessageID);

            if (lstTicketMessages.Count == 0)
                return;

            
            Control dvImages = e.Row.FindControl("dvImages");
            HyperLink aImage = (HyperLink)e.Row.FindControl("aImage");
            Image imgImage = (Image)e.Row.FindControl("imgImage");


            if (lstTicketMessages[0].lstTicketImages.Count == 0)
                dvImages.Visible = false;
            else
            {
                dvImages.Visible = true;
                aImage.NavigateUrl = "./TicketImages/" + lstTicketMessages[0].lstTicketImages[0].TicketImage;
                aImage.Target = "_blank";

                imgImage.ImageUrl = "./getImage.ashx?image=./TicketImages/" + lstTicketMessages[0].lstTicketImages[0].TicketImage + "&w=100&h=100&color=white";

            }

        }
    }
}